package com.sunb2b.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.sunb2b.entity.*;
/**
 * A data access object (DAO) providing persistence and search support for
 * Category entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.sunb2b.dao.Category
 * @author MyEclipse Persistence Tools
 */

public class CategoryDAO extends HibernateDaoSupport {
    private static final Logger log = LoggerFactory
            .getLogger(CategoryDAO.class);
    // property constants
    public static final String NAME = "name";
    public static final String DESCRIPTION = "description";
    public static final String LIST_TEMPLATE = "listTemplate";
    public static final String DETAIL_TEMPLATE = "detailTemplate";
    public static final String PRODUCT_EDITOR = "productEditor";
    public static final String LIST_PATH = "listPath";
    public static final String DETAIL_PATH = "detailPath";

    protected void initDao() {
        // do nothing
    }

    public void save(Category transientInstance) {
        log.debug("saving Category instance");
        try {
            getHibernateTemplate().saveOrUpdate(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    public void delete(Category persistentInstance) {
        log.debug("deleting Category instance");
        try {
            getHibernateTemplate().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    public Object delete(final String[] ids){
    	return getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session s)
					throws HibernateException, SQLException {
				for (String id : ids){
					s.createQuery("delete from Category where id like '" + id + "%'").executeUpdate();
				}
				return null;
			}
    		
    	});
    }

    public Category findById(java.lang.String id) {
        log.debug("getting Category instance with id: " + id);
        try {
            Category instance = (Category) getHibernateTemplate().get(
                    "com.sunb2b.entity.Category", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    public List findSubCategories(String id){
        log.debug("getting sub categories list instance with id: " + id);
        DetachedCriteria dc = DetachedCriteria.forClass(Category.class);
        dc.add(Restrictions.like("id", id + "___"));// _ is the wildcard of SQL.
        return getHibernateTemplate().findByCriteria(dc);
    }

    public String getMaxSubId(final String id){
        log.debug("getting sub categories list instance with id: " + id);
        return (String) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session s) throws HibernateException,
                    SQLException {
                String q = "select max(id) from Category where id like '" + id + "___'";
                Object o = s.createQuery(q).uniqueResult();
                if(o==null){
                    return null;
                }
                return (String)o;
            }
        });
    }
    
    public List findByExample(Category instance) {
        log.debug("finding Category instance by example");
        try {
            List results = getHibernateTemplate().findByExample(instance);
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    public List findByProperty(String propertyName, Object value) {
        log.debug("finding Category instance with property: " + propertyName
                + ", value: " + value);
        try {
            String queryString = "from Category as model where model."
                    + propertyName + "= ?";
            return getHibernateTemplate().find(queryString, value);
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List findByName(Object name) {
        return findByProperty(NAME, name);
    }

    public List findByDescription(Object description) {
        return findByProperty(DESCRIPTION, description);
    }

    public List findByListTemplate(Object listTemplate) {
        return findByProperty(LIST_TEMPLATE, listTemplate);
    }

    public List findByDetailTemplate(Object detailTemplate) {
        return findByProperty(DETAIL_TEMPLATE, detailTemplate);
    }

    public List findByProductEditor(Object productEditor) {
        return findByProperty(PRODUCT_EDITOR, productEditor);
    }

    public List findByListPath(Object listPath) {
        return findByProperty(LIST_PATH, listPath);
    }

    public List findByDetailPath(Object detailPath) {
        return findByProperty(DETAIL_PATH, detailPath);
    }

    public List findAll() {
        log.debug("finding all Category instances");
        try {
            String queryString = "from Category";
            return getHibernateTemplate().find(queryString);
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public Category merge(Category detachedInstance) {
        log.debug("merging Category instance");
        try {
            Category result = (Category) getHibernateTemplate().merge(
                    detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Category instance) {
        log.debug("attaching dirty Category instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(Category instance) {
        log.debug("attaching clean Category instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public static CategoryDAO getFromApplicationContext(ApplicationContext ctx) {
        return (CategoryDAO) ctx.getBean("CategoryDAO");
    }
}
